package server;


import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * Minicat的主类
 */
public class Bootstrap {

    /**定义socket监听的端口号*/
    private int port = 8080;

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }


    /**
     * Minicat启动需要初始化展开的一些操作
     */
    public void start() throws Exception {

        // 加载解析相关的配置，web.xml
        loadServlet();
        loadContext();


        // 定义一个线程池
        int corePoolSize = 10;
        int maximumPoolSize =50;
        long keepAliveTime = 100L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();


        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );





        /*
            完成Minicat 1.0版本
            需求：浏览器请求http://localhost:8080,返回一个固定的字符串到页面"Hello Minicat!"
         */
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("=====>>>Minicat start on port：" + port);

        /*while(true) {
            Socket socket = serverSocket.accept();
            // 有了socket，接收到请求，获取输出流
            OutputStream outputStream = socket.getOutputStream();
            String data = "Hello Minicat!";
            String responseText = HttpProtocolUtil.getHttpHeader200(data.getBytes().length) + data;
            outputStream.write(responseText.getBytes());
            socket.close();
        }*/


        /**
         * 完成Minicat 2.0版本
         * 需求：封装Request和Response对象，返回html静态资源文件
         */
        /*while(true) {
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            response.outputHtml(request.getUrl());
            socket.close();

        }*/


        /**
         * 完成Minicat 3.0版本
         * 需求：可以请求动态资源（Servlet）
         */
        /*while(true) {
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            // 静态资源处理
            if(servletMap.get(request.getUrl()) == null) {
                response.outputHtml(request.getUrl());
            }else{
                // 动态资源servlet请求
                HttpServlet httpServlet = servletMap.get(request.getUrl());
                httpServlet.service(request,response);
            }

            socket.close();

        }
*/

        /*
            多线程改造（不使用线程池）
         */
        /*while(true) {
            Socket socket = serverSocket.accept();
            RequestProcessor requestProcessor = new RequestProcessor(socket,servletMap);
            requestProcessor.start();
        }*/



        System.out.println("=========>>>>>>使用线程池进行多线程改造");
        /*
            多线程改造（使用线程池）
         */
        while(true) {

            Socket socket = serverSocket.accept();
            RequestProcessor requestProcessor = new RequestProcessor(socket, mapperElement, contextMap, servletMap);
            //requestProcessor.start();
            threadPoolExecutor.execute(requestProcessor);
        }



    }


    private Map<String,HttpServlet> servletMap = new HashMap<String,HttpServlet>();

    /**
     * 加载解析web.xml，初始化Servlet
     */
    private void loadServlet() {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("web.xml");
        SAXReader saxReader = new SAXReader();

        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();

            List<Element> selectNodes = rootElement.selectNodes("//servlet");
            for (int i = 0; i < selectNodes.size(); i++) {
                Element element =  selectNodes.get(i);
                // <servlet-name>lagou</servlet-name>
                Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
                String servletName = servletnameElement.getStringValue();
                // <servlet-class>server.LagouServlet</servlet-class>
                Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
                String servletClass = servletclassElement.getStringValue();


                // 根据servlet-name的值找到url-pattern
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                // /lagou
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();
                servletMap.put(urlPattern, (HttpServlet) Class.forName(servletClass).newInstance());

            }



        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }

    private Map<String,String> contextMap = new HashMap<>();
    private Mapper mapperElement = new Mapper();
    /**
     * 加载解析server.xml，初始化Context
     */
    private void loadContext() {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("server.xml");
        SAXReader saxReader = new SAXReader();

        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();

            List<Element> serverNodes = rootElement.selectNodes("//Service");
            for (int i = 0; i < serverNodes.size(); i++) {
                Element serverElement =  serverNodes.get(i);
                List<Element> engineNodes = serverElement.selectNodes("//Engine");
                for(Element engineElement : engineNodes){
                    List<Element> hostNodes = engineElement.selectNodes("//Host");

                    for(Element hostElement : hostNodes){
                        Mapper.MappedHost mappedHost = new Mapper.MappedHost();
                        mappedHost.name = hostElement.attributeValue("name");
                        mappedHost.obj = hostElement.attributeValue("appBase");
                        mapperElement.hostMap.put(mappedHost.name, mappedHost);

                        List<Element> contextNodes = hostElement.selectNodes("//Context");

                        for(Element contextElement : contextNodes){
                            Mapper.MappedContext mappedContext = new Mapper.MappedContext();
                            mappedContext.name = contextElement.attributeValue("path");
                            String path = contextElement.attributeValue("docBase");

                            //每个context，先找到web.xml里配置的Servlet，再实例化
                            mappedContext.obj = getServlet(path);
                            mappedHost.contextMap.put(mappedContext.name, mappedContext);

                            contextMap.put(contextElement.attributeValue("path"), contextElement.attributeValue("docBase"));

                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据context路径找到servlet
     *
     * */
//    private Object getServlet1(String path) throws Exception {
//
//        String webXml = path + "\\web.xml";
//        SAXReader saxReader = new SAXReader();
//        Document document = saxReader.read(new File(webXml));
//        Element rootElement = document.getRootElement();
//
//        List<Element> selectNodes = rootElement.selectNodes("//servlet");
//        for (int i = 0; i < selectNodes.size(); i++) {
//            Element element =  selectNodes.get(i);
//            // <servlet-name>lagou</servlet-name>
//            Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
//            String servletName = servletnameElement.getStringValue();
//            // <servlet-class>server.LagouServlet</servlet-class>
//            Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
//            String servletClass = servletclassElement.getStringValue();
//
//
//            // 根据servlet-name的值找到url-pattern
//            Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
//            // /lagou
//            String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();
//            httpServlet = (HttpServlet) Class.forName(servletClass).newInstance();
//        }
//        return httpServlet;
//    }

    /**
     * 根据context路径找到servlet
     *
     * */
    private Object getServlet(String path) throws Exception {

        ClassloaderExpand classloaderExpand = new ClassloaderExpand();

        classloaderExpand.setLocation(path + "\\server\\");
        Class cl = classloaderExpand.findClass("LagouServlet");
        Object o = cl.newInstance();
        return o;
    }


    /**
     * Minicat 的程序启动入口
     * @param args
     */
    public static void main(String[] args) {
        Bootstrap bootstrap = new Bootstrap();
        try {
            // 启动Minicat
            bootstrap.start();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }






    /**

     开发Minicat V4.0，在已有Minicat基础上进一步扩展，模拟出webapps部署效果 磁盘上放置一个webapps目录，webapps中可以有多个项目，例如demo1、demo2、demo3... 每个项目中含有servlet，可以根据请求url定位对应servlet进一步处理。

     作业具体要求参考以下链接文档：

     https://gitee.com/lagouedu/alltestfile/raw/master/tomcat/Tomcat%E4%BD%9C%E4%B8%9A%E5%A4%A7%E9%A2%98.pdf

     作业资料说明：

     1、提供资料：工程代码和自己的webapps以及访问路径、功能演示和原理讲解视频。

     2、讲解内容包含：题目分析、实现思路、代码讲解。

     3、效果视频验证：实现模拟tomcat多项目部署效果，访问多个不同项目可获得动态返回的内容。
     *******************************************************************************************************************

     单个tomcat下支持多个web项目
     首先一个tomcat只有一个web.xml（用来配置servlet，listener等）
     编写server.xml，这里有host，context等
     host表示一个虚拟主机（即站点）
     context表示一个web应用（web项目），其path属性就是url中第一个值。即根据第一个url可以将同一站点同一端口下的url打到不同的webapps下的web应用目录里
     解析server.xml，注册各级的映射关系：Mapper类—>Host->Context->Wrapper->Servlet
     最后每个web应用的servlet的处理请求后返回




     *
     *
     */






}
